package com.elicitor.listner;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.File;


public class WaveData {
    
    String savePath;

    public String saveToFile(String name, AudioFileFormat.Type fileType,
                              AudioInputStream audioInputStream) {
        System.out.println("Saving...");
        if (null == name || null == fileType || audioInputStream == null) {
            return "There is a null value for name or fileType or audioInputStream";
        }
        File myFile = new File( name+"." + fileType.getExtension());
        // reset to the beginnning of the captured data
        try {
            audioInputStream.reset();
        } catch (Exception e) {
            return "There is an error "+e;
        }
        int i = 1;
        while (myFile.exists()) {
            if (myFile.getName().length() == 9){
            String tempType = ("" + myFile.getName()).substring(5);
            String tempName = ("" + myFile.getName()).substring(0,4);
            String fileName = tempName+i+tempType;
            myFile = new File(fileName);
            }
            else{
            String tempType = ("" + myFile.getName()).substring(6);
            String tempName = ("" + myFile.getName()).substring(0,4);
            String fileName = tempName+i+tempType;
            myFile = new File(fileName);
                
            }
            
            
            i++;
        }
        try {
            AudioSystem.write(audioInputStream, fileType, myFile);
        } catch (Exception ex) {
            return "There is an error "+ex;
        }
        System.out.println("Saved " + myFile.getAbsolutePath());
        savePath = myFile.getAbsolutePath();
        return savePath;
    }





}
